<template>
  <n-grid :cols="12" item-responsive responsive="screen">
    <n-gi span="12 m:8 l:6" offset="0 m:2 l:3">
      <n-button class="my-2" color="#2980b9" style="width:100%"
        @click="showChapterModal = true, chapterParam.chapterID = null, chapterParam.title = null, chapterModalTitle = '新增章节'">
        添加新章节</n-button>
    </n-gi>
    <n-gi span="12 m:8 l:6" offset="0 m:2 l:3">
      <n-empty description="你什么也找不到" v-if="chapterMediaList && chapterMediaList.length == 0">
        <template #extra>
          <n-button size="small" @click="showChapterModal = true, chapterParam.chapterID = null, chapterParam.title = null, chapterModalTitle = '新增章节'">
            添加点新章节吧
          </n-button>
        </template>
      </n-empty>
      <n-collapse :default-expanded-names="[0]">
        <template v-for="(chapter,index) in chapterMediaList">
          <n-collapse-item :title="chapter.title" :name='index' class="p-3 rounded"
            style="background-color:#ecf0f1">
            <template #header-extra v-if="(chapter.media.length!=0)">
                  共{{chapter.media.length}}项
            </template>
            <template #header-extra v-if="(chapter.media.length==0)">
                  空章节
            </template>
            <n-space justify="end">
              <n-button class="my-2" color="#2980b9" @click="handleEditChapter(chapter.chapterID, chapter.title)">编辑章节
              </n-button>
              <n-button class="my-2" color="#2980b9" @click="uploadMedia(chapter.chapterID)">上传媒体</n-button>
              <n-button class="my-2" color="#c0392b" @click="handleDeleteChapter(chapter.chapterID)">删除章节</n-button>
            </n-space>
            <!-- 如果无媒体 -->
            <n-empty description="没有任何媒体哦" v-if="!chapter.media.length">
              <template #extra>
                <n-button @click="uploadMedia(chapter.chapterID)">
                  上传媒体
                </n-button>
              </template>
            </n-empty>
            <n-list class=" rounded">
              <template v-for="media in chapter.media">
                <n-list-item class="mx-4">
                <template #prefix>
                  <n-avatar>
                    <!-- {{media.type}} -->
                      <n-icon v-if="media.type == 'pdf'" :component="DocumentPdf24Filled" size="40" :depth="1" />
                      <n-icon v-else-if="media.type == 'mov' || media.type == 'mp4' || media.type == 'mkv'" :component="MoviesAndTv20Filled" size="40" :depth="1" />
                      <n-icon v-else-if="media.type == 'jpg' || media.type == 'png' || media.type == 'jpeg'" :component="InsertPhotoFilled" size="40" :depth="1" />
                      <n-icon v-else :component="FileTrayFull" size="40" :depth="1" />
                  </n-avatar>
                </template>
                <n-thing>
                  <template #header>
                    <n-button text @click="handleViewFile(media.storgeLocation,media.type)">{{media.basicName}}</n-button>
                  </template>
                  <template #header-extra>
                  <n-space>
                    <n-tag type="info">
                      积分:{{media.credit}}
                    </n-tag>
                    <n-tag type="info">
                      完成人数:{{(media.number==null?0:media.number)+' / '+ courseStudentNumber}}
                    </n-tag>
                    <n-button strong secondary type="info" size="small" @click="handleCount(media.MID)">
                      未完成统计
                    </n-button>
                    </n-space>
                  </template>
                  <template #action>
                    <n-space justify="space-between">
                      <n-text> </n-text>
                      <n-space justify="end">
                        <n-button size="small" @click="handleEditMedia(media.MID,media.basicName,media.credit)">
                          <template #icon>
                            <n-icon>
                              <Edit16Filled />
                            </n-icon>
                          </template>
                          编辑文件
                        </n-button>
                        <n-button tag="a" size="small" :href="'/api'+media.storgeLocation" target="_blank">
                          <template #icon>
                            <n-icon>
                              <CloudDownload />
                            </n-icon>
                          </template>
                          下载文件
                        </n-button>
                        <n-button size="small" @click="handelDeleteMedia(media.MID)" type="error" secondary>
                          <template #icon>
                            <n-icon>
                              <Delete20Filled />
                            </n-icon>
                          </template>
                          删除文件
                        </n-button>
                      </n-space>
                    </n-space>
                  </template>
                </n-thing>
              </n-list-item>
              </template>
            </n-list>
          </n-collapse-item>
        </template>
      </n-collapse>
    </n-gi>
  </n-grid>
  <!-- pdf预览 -->
  <n-modal v-model:show="showPdfModal" preset="card" title="预览PDF" style="height:100vh" class="overflow-scroll">
    <PdfView :pdfUrl="pdfUrl" />
  </n-modal>
  <!-- 视频预览 -->
  <n-modal v-model:show="showVedioModal" preset="card" title="预览视频" style="max-width: 800px">
    <VedioView :vedioUrl="vedioUrl"
      :mediaID="1"></VedioView>
  </n-modal>
  <!--图片预览-->
  <n-modal v-model:show="showPicModal" preset="card" title="预览图片" style="max-width: 800px">
    <img :src="imgUrl" alt="previewPic" width="800">
  </n-modal>
  <!-- 章节未完成名单 -->
  <n-modal v-model:show="showCountModal" preset="card" title="未完成名单" style="height:100vh" class="overflow-scroll">
    <countMedia :MID="MID" />
  </n-modal>
  <!-- 添加章节表单 -->
  <n-modal v-model:show="showChapterModal" :show-icon="false" preset="dialog" :title="chapterModalTitle">
    <n-form :model="chapterParam" :rules="chapterFormRules" ref="chapterFormRef" label-placement="left"
      :label-width="80" class="py-4">
      <n-form-item label="章节名" path="title">
        <n-input v-model:value="chapterParam.title" />
      </n-form-item>
    </n-form>
    <template #action>
      <n-space>
        <n-button @click="() => (showChapterModal = false)">取消</n-button>
        <n-button type="info" :loading="formBtnLoading" @click="confirmChapterEditForm">确定</n-button>
      </n-space>
    </template>
  </n-modal>
  <!-- 媒体上传表单 -->
  <n-modal v-model:show="showMediaModal" :show-icon="false" preset="dialog" title="上传媒体">
    <n-form :model="mediaParam" :rules="mediaFormRules" ref="mediaFormRef" label-placement="left"
      :label-width="80" class="py-4">
    <n-form-item label="文件" path="file">
      <n-upload ref="uploadRef" action="/teacher/teacher_chapter_media/addMedia" :default-upload="false"
        :custom-request="customRequest">
        <n-button>选择文件</n-button>
      </n-upload>
    </n-form-item>
    <n-form-item label="媒体标题" path="title">
        <n-input v-model:value="mediaParam.title" />
    </n-form-item>
    <n-form-item label="积分" path="credit">
        <n-input-number v-model:value="mediaParam.credit" />
    </n-form-item>
    </n-form>
    <template #action>
      <n-space>
        <n-button @click="() => (showMediaModal = false)">取消</n-button>
        <n-button type="info" :loading="formBtnLoading" @click="handleUploadMedia">上传</n-button>
      </n-space>
    </template>
  </n-modal>
  <!-- 媒体修改表单 -->
  <n-modal v-model:show="showMediaEditModal" :show-icon="false" preset="dialog" title="修改媒体信息">
    <n-form :model="mediaEditParam" :rules="mediaEditFormRules" ref="mediaEditFormRef" label-placement="left"
      :label-width="80" class="py-4">
    <n-form-item label="媒体标题" path="title">
        <n-input v-model:value="mediaEditParam.title" />
    </n-form-item>
    <n-form-item label="积分" path="credit">
        <n-input-number v-model:value="mediaEditParam.credit" />
    </n-form-item>
    </n-form>
    <template #action>
      <n-space>
        <n-button @click="() => (showMediaEditModal = false)">取消</n-button>
        <n-button type="info" :loading="formBtnLoading" @click="confirmMediaEditForm">修改</n-button>
      </n-space>
    </template>
  </n-modal>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import { CloudDownload,FileTrayFull} from '@vicons/ionicons5';
import {Delete20Filled ,Edit16Filled ,DocumentPdf24Filled,MoviesAndTv20Filled} from '@vicons/fluent';
import {InsertPhotoFilled} from '@vicons/material';
import PdfView from './pdfView.vue';
import VedioView from './vedioView.vue';
import { uploadSection } from '@/plugins/upload.js';
import { UploadCustomRequestOptions, useDialog, useMessage } from 'naive-ui';
import { useRoute } from 'vue-router';
import { http } from '@/utils/http/axios';
import countMedia from './countMedia.vue';

const pdfUrl = ref('');
const vedioUrl = ref('');
const imgUrl =ref('');
const showPdfModal = ref(false);
const showVedioModal = ref(false);
const showPicModal = ref(false);
const showChapterModal = ref(false);
const showMediaModal = ref(false);
const showMediaEditModal =ref(false);
const uploadRef = ref();
const message = useMessage();
const route = useRoute();
const formBtnLoading = ref();
const colList = ref([]);
const chapterModalTitle = ref('');
const dialog = useDialog();
const courseStudentNumber = ref('');
const MID = ref();
const showCountModal = ref(false);

const chapterParam = reactive(
  {
    chapterID: null,
    title: null,
    courseID: route.params.courseID
  }
);
const chapterFormRef: any = ref(null);
const chapterFormRules = {
  title: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入章节名'
  }
}

const mediaFormRef=ref();
const mediaParam = reactive(
  {
    title:null,
    chapterID:null,
    credit:null,
  }
)
const mediaFormRules={
  title:{
    required:true,
    trigger: ['blur', 'input'],
    message: '请输入标题'
  },
  chapterID:{
    required: true,
    message: '请选择章节'
  },
  credit:{
    required: true,
    type: 'number',
    trigger: ['blur', 'input'],
    message: '请输入积分'
  }
}

const mediaEditFormRef=ref();
const mediaEditParam = reactive(
  {
    title:null,
    MID:null,
    credit:null,
  }
)
const mediaEditFormRules={
  title:{
    required:true,
    trigger: ['blur', 'input'],
    message: '请输入标题'
  },
  MID:{
    required: true,
    message: '请媒体ID'
  },
  credit:{
    required: true,
    type: 'number',
    trigger: ['blur', 'input'],
    message: '请输入积分'
  }
}

const chapterMediaList = ref();

onMounted(
  async () => {
    chapterMediaList.value = await http.request(
      {
        url: '/teacher/teacher_chapter_media/list',
        method: 'get',
        params: { courseID: route.params.courseID }
      }
    );

    console.log(chapterMediaList);
    colList.value = chapterMediaList.value.map(v => { return v.chapterID })
    console.log(colList.value);
    let rList = [];
    for(let c in colList.value){
      rList.push(colList.value[c]);
    }
    colList.value = rList;
    console.log(colList);
    let courseInfo = sessionStorage.getItem('courseInfo');
    
    if(courseInfo != null ){
      let ci = JSON.parse(courseInfo);
      console.log(ci);
      if(ci !=null)
        courseStudentNumber.value = ci.studentNumber;
    }
  }
)

async function reloadList(){
  chapterMediaList.value = await http.request(
      {
        url: '/teacher/teacher_chapter_media/list',
        method: 'get',
        params: { courseID: route.params.courseID }
      }
    );

    console.log(chapterMediaList);
    colList.value = chapterMediaList.value.map(v => { return v.chapterID });
}


function confirmChapterEditForm(e) {
  e.preventDefault();
  formBtnLoading.value = true;
  chapterFormRef.value.validate((errors) => {
    if (!errors) {
      //message.success('新建成功');
      let params = chapterParam;
      let url = '';
      if (params.chapterID) {
        url = '/teacher/teacher_chapter_media/editChapter'
      } else {
        url = '/teacher/teacher_chapter_media/addChapter'
      }
      http.request({
        url: url,
        method: 'post',
        params
      }).then(
        () => {
          message.success('成功');
          showChapterModal.value = false;
          reloadList();
        }
      );
    } else {
      message.error('请填写完整信息');
    }
    formBtnLoading.value = false;
  });
}

function confirmMediaEditForm(e){
  e.preventDefault();
  formBtnLoading.value = true;
  mediaEditFormRef.value.validate((errors) => {
    if (!errors) {
      //message.success('新建成功');
      let params = mediaEditParam;
      let url = '';
      url = '/teacher/teacher_chapter_media/editMedia'
      http.request({
        url: url,
        method: 'post',
        params
      }).then(
        () => {
          message.success('成功');
          showMediaEditModal.value = false;
          reloadList();
        }
      );
    } else {
      message.error('请填写完整信息');
    }
    formBtnLoading.value = false;
  });
}

function handleViewFile(storgeLocation,type){
  if(type == 'pdf'){
    openPdf(storgeLocation);
  }
  else if(type == 'mov' || type == 'mp4' || type == 'mkv'){
    openVedio(storgeLocation);
  }
  else if(type == 'jpg' || type == 'png' || type == 'jpeg'){
    openPic(storgeLocation);
  }
  else {
    message.warning('不受支持的类型');
  }
}

const openPdf = (url) => {
  showPdfModal.value = true;
  pdfUrl.value = '/api'+url
}

const openVedio = (url) =>{
  showVedioModal.value = true;
  vedioUrl.value = '/api'+url;
}

const openPic = (url) =>{
  showPicModal.value = true;
  imgUrl.value = '/api'+url;
}

const customRequest = ({
  file,
  data,
  headers,
  withCredentials,
  action,
  onFinish,
  onError,
  onProgress
}: UploadCustomRequestOptions) => {
  data;
  headers;
  withCredentials;
  console.log(file);
  uploadSection(
    {
      url: action,
      filename: 'file',
      onUploadProgress: (option) => { onProgress({ percent: Math.ceil(option.loaded / option.total * 100) }) },
      file: file.file,
      params:mediaParam
    }
  ).then((res) => {
    console.log(res);
    message.success('成功！');
    showMediaModal.value = false;
    reloadList();
    onFinish();
  }
  ).catch(
    (error) => {
      console.log(error);
      message.success('失败！')
      onError();
    }
  )
}


function handleEditChapter(chapterID, title) {
  chapterParam.chapterID = chapterID;
  chapterParam.title = title;
  showChapterModal.value = true;
  chapterModalTitle.value = "编辑章节"
}

function handleDeleteChapter(chapterID) {
  dialog.info({
    title: '提示',
    content: `您想删除此章节吗`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      http.request({
        url: '/teacher/teacher_chapter_media/deleteChapter',
        method: 'get',
        params: { chapterID: chapterID }
      }).then(
        () => {
          message.success('成功');
          reloadList();
          showChapterModal.value = false;
        }
      );
    },
    onNegativeClick: () => { },
  }
  )
}

function handleEditMedia(MID,title,credit){
  mediaEditParam.MID = MID;
  mediaEditParam.title = title;
  mediaEditParam.credit = credit;
  showMediaEditModal.value = true;
}

function handelDeleteMedia(MID){
  dialog.info({
    title: '提示',
    content: `您想删除此章节吗`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      http.request({
        url: '/teacher/teacher_chapter_media/deleteMedia',
        method: 'get',
        params: { MID: MID }
      }).then(
        () => {
          message.success('成功');
          reloadList();
          showChapterModal.value = false;
        }
      );
    },
    onNegativeClick: () => { },
  }
  )
}

function uploadMedia(chapterID) {
  mediaParam.credit =null;
  mediaParam.title = null;
  showMediaModal.value= true;
  mediaParam.chapterID = chapterID;
}

function handleUploadMedia(e) {
  e.preventDefault();
  formBtnLoading.value = true;
  mediaFormRef.value.validate((errors) => {
    if (!errors) {
  uploadRef.value?.submit();
  } else {
      message.error('请填写完整信息');
    }
    formBtnLoading.value = false;
  });
}

function handleCount(currentMID){
  MID.value = currentMID;
  showCountModal.value=true;
}
</script>

<style scoped>
</style>